package com.example.demo.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.demo.Utils.CreateJWT;
import com.example.demo.Utils.PasswordEncrypt;
import com.example.demo.Utils.RoleFactory;
import com.sun.deploy.net.HttpResponse;
import io.jsonwebtoken.Claims;
import jdk.nashorn.internal.parser.JSONParser;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.example.demo.pojo.User;
import com.example.demo.service.UserService;

/**
 * 用户控制器
 * 
 * @author hasee
 * @version 0.1
 */

@CrossOrigin
@Controller
@RequestMapping("/user")
public class UserController {

	@Autowired
	private UserService userService;
	

	@ResponseBody
	@GetMapping(value = "/findUserById{id}", produces = "text/plain;charset=utf-8")
	public User findUserById(@RequestParam("id") int id) {
		User user = this.userService.findUserById(id);
		return user;
	}


	/*
	 * 注册时检验用户账号是否重复的接口
	 * */
	@RequestMapping(value = "/checkuseraccountrepeat")
	@ResponseBody
	public String checkRegisterUserAccountRepeat(@RequestBody User user) {
		String returnMSG="";
		int msgFromService;
		System.out.println(user);
		User userInfo=new User();
		userInfo.setUserAccount(user.getUserAccount());
		msgFromService=userService.checkRegisterUserAccountRepeat(userInfo);
		if(msgFromService>0) {
			returnMSG="用户账号已被注册";
		}else {
			returnMSG="1";
		}
		return returnMSG;

	}

	/*
	* 用户注册的功能接口
	* */
	@RequestMapping(value = "/register")
	// @ResponseBody注解是后台做出回应前端的返回体（下面的方法中包含多个逻辑操作）
	// @RequestBody注解是前端传递到后台的请求数据（可以是json对象。可以是json数据，用@param注解接收）
	@ResponseBody
	public int registerAddUser(@RequestBody User user) {
		System.out.println(user);
		int row;
		int result;
		row = userService.registerAddUser(user);
		String msg = "";
		if (row > 0) {
			System.out.println("注册成功!");
			result = 1;
		} else {
			System.out.println("注册失败!请稍后重试");
			result = 0;
		}
		return result;
	}

	/*
	 * 用户在web端登录请求的接口
	 * 1.0-普通post方式登录（弃用）
	 * 2.0-token令牌登录验证（实现）
	*/
	@RequestMapping(value = "/logincheck")
	@ResponseBody
	public Integer checkToken(@RequestBody User user,HttpServletRequest request) {
		//返回结果
		String result;
		int row;
		// 打印前端传递的用户token数据
		System.out.println(user.getUserTokenWeb());
		System.out.println("前端的request："+request);
		System.out.println("前端的request："+request.getHeader("authorization"));
		System.out.println("前端的request："+request.getHeader("Authorization"));
		System.out.println("前端的request："+request.getHeader("Bearer"));
		//解析token
		CreateJWT createJWT = new CreateJWT();
		Claims claims = createJWT.analysisToken(request,user.getUserAccount());
		// 调用service方法
		result = userService.checkToken(claims);
		if (result.equals("ok")) {
			System.out.println("登录成功!");
			row = 1;
		} else {
			System.out.println("登录失败!");
			row = 0;
		}
		// String msg="";
		return row;
	}

	/**
	 * 测试token
	 * **/
	@RequestMapping(value = "/testtoken")
	@ResponseBody
	public String testToken(HttpServletRequest request,@RequestBody User user,HttpServletResponse response){
		String result = null;
		CreateJWT createJWT = new CreateJWT();
		System.out.println(user.getUserPassword());
//		result = createJWT.analysisToken(request,user.getUserAccount());
		System.out.println("在controller中打印："+result);
		response.setHeader("token",result);
		return result;
	}

	/*
	* 用户的客户端中cookie保存的token已过期或被清除
	* 重新登录，给予用户token
	* */
	@RequestMapping(value = "/login")
	@ResponseBody
	public String createTokenAndLogin(@RequestBody User user) {
		String result;
		int row;
		String checkBack;
		// 打印前端传递的用户信息json数据
		System.out.println(user);
		// 调用service方法
		result = userService.createTokenAndLogin(user.getUserAccount(),user.getUserPassword());
		if (result!=null) {
			System.out.println("登录成功!");
		} else {
			System.out.println("登录失败!");
			result="登录失败";
		}
		return result;
	}



	/*
	 * 用户中心显示该用户的个人信息等
	 * 1.0已显示信息，但逻辑算法需优化
	 * 2.0参见bilibil网站的个人中心（未实现）
	 */
	@RequestMapping(value = "/center/userInfo")
	@ResponseBody
	public List<User> findUserBasicInfo(@RequestBody User user,HttpServletRequest request) {
		boolean result = false;
		String userAccount;
//		int row;
		List<User> listResult = null;
		CreateJWT createJWT = new CreateJWT();
		RoleFactory roleFactory = new RoleFactory();
		result = roleFactory.checkRoleOfUser(createJWT.analysisToken(request,user.getUserAccount()));
		System.out.println(result);
		if(result){
			// 打印传递过来的user
			System.out.println(user);
			// 创建一个user对象
			User userInfo = new User();
			// 得到用户账号
			userInfo.setUserAccount(user.getUserAccount());
			userAccount = user.getUserAccount();
			// 调用service方法
			listResult = userService.findUserBasicInfo(userInfo);
			System.out.println("controller将返回的信息是：" + listResult);
			return listResult;
		}else{
			return listResult;
		}
	}

	
	/*
	 * Android
	 * 
	 * android
	 * 
	 * */
	

//	@RequestMapping(value = "/androidlogin")
//	@ResponseBody
////	@RequestParam("id")int id,@RequestParam("userAccount")String userAccount,@RequestParam("userPassword")String userPassword,@RequestParam("userPower")int userPower
//	public Integer androidLoginCheck(@RequestBody User user) {
//		// �����������
//		String result;
//		int row;
//		String checkBack;
//		// ��ӡ���յ�������
//		System.out.println(user);
//		// ����һ��user������������userController���ݵ��÷���������
//		User userInfo = new User();
//		// �õ��û����˻�������
////		userInfo.setUserAccount(userAccount);
////		userInfo.setUserPassword(userPassword);
//		userInfo.setUserAccount(user.getUserAccount());
//		userInfo.setUserPassword(user.getUserPassword());
//		// ���õ���ֵ�ش����ӿ�ʵ���࣬�ӿ�ʵ����ִ�о������
//		result = userService.checkToken(userTokenWeb);
//		// result�õ�����UserServiceImpl��loginCheck�����ķ���ֵ
//		// ����loginCheck��������ʲô������result��ʲô���ͽ���
//		// ��Ȼ�ᱨ��ָ��
//		if (result.equals("ok")) {
//			System.out.println("�û���¼�ɹ�");
//			row = 1;
//		} else {
//			System.out.println("���û���δע��");
//			row = 0;
//		}
//
//		return row;
//	}


	/*
	* 后台管理员操作用户的功能接口
	* */

	@RequestMapping(value = "/userlist")
	@ResponseBody
	public List<User> findUserlist(){
		List<User> userlist=new ArrayList<>();
		userlist=userService.findUserList();
		System.out.println(userlist);
		return userlist;

	}

	/*
	 * 更新用户信息的接口
	 * */
	@RequestMapping(value = "/backupdateuserinfo")
	@ResponseBody
	public String backUserUpdataInfo(@RequestBody User user) {
		String returnMSG="更新未能完成";
		int msgFromService;
		System.out.println("接收到的用户信息："+user);
		User userInfo=new User();
		userInfo.setUserAccount(user.getUserAccount());
		userInfo.setUserName(user.getUserName());
		userInfo.setUserPower(user.getUserPower());
		userInfo.setUserProfile(user.getUserProfile());
		msgFromService=userService.backUserUpdataInfo(userInfo);
		if(msgFromService>0) {
			returnMSG="1";
		}else {
			returnMSG="更新未能完成!";
		}
		return returnMSG;
	}

	/**
	 * 更改用户的启用状态（禁用、启用）
	 * **/

	@RequestMapping(value = "changeuserstate")
	@ResponseBody
	public int changeUserState(@RequestBody String body){
		int result = 0;
		String userState = null;
		String userAccount = null;
		System.out.println(body);
		try {
			JSONObject json = new JSONObject();
			json = JSONObject.parseObject(body);
			System.out.println(json);
			userState = json.getString("userState");
			userAccount = json.getString("userAccount");
			System.out.println(userState+"\t"+userAccount);
			result = userService.changeUserState(userState,userAccount);
			if(result > 0){
				return result;
			}
		}catch (Exception e){
			System.out.println("controller中的changeUserState发生异常:"+e);
			result = 0;
			return result;
		}
		return result;
	}

	/*
	 * 删除用户信息的接口,已被启用、禁用用户替代
	 * */
	@RequestMapping(value = "/deleteuser")
	@ResponseBody
	public String deleteUserFromBack(@RequestBody User user) {
		String returnMSG="操作无效";
		int msgFromService;
		System.out.println(user);
		User userInfo=new User();
		userInfo.setUserAccount(user.getUserAccount());
		userInfo.setUserName(user.getUserName());
		msgFromService=userService.deleteUserFromBack(userInfo);
		if(msgFromService>0) {
			returnMSG="1";
		}else {
			returnMSG="删除失败！";
		}
		return returnMSG;
	} 

}
